//
//  HHQReaderViewController.m
//  QRTest
//
//  Created by shiwanjun on 14-4-17.
//  Copyright (c) 2014年 com.gewara. All rights reserved.
//

#import "HHQReaderViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ZBarSDK.h"
#import "UIView+Rect.h"

#define RGBCOLOR(r,g,b) \
[UIColor colorWithRed:r/256.f green:g/256.f blue:b/256.f alpha:1.f]

@interface HHQReaderViewController ()<AVCaptureMetadataOutputObjectsDelegate,ZBarReaderViewDelegate>
/**
 *  iOS7自带扫描
 */
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;

/**
 *  ZBar 二维码扫描
 */
@property(nonatomic,strong)ZBarReaderView *zReaderView;

//播放
@property(nonatomic,strong)AVAudioPlayer *player;
/**
 *  贴在扫描页面的
 */
@property(nonatomic,strong)UIView *overView;

@property(nonatomic,strong)UIImageView *lineImageView;
@property(nonatomic,strong)UIImageView *scaningImageView;

@property(nonatomic,strong)UIImageView *cameraTopImageView;
@property(nonatomic,strong)UIImageView *camearBottomImageView;

@property(nonatomic,strong)UIView *coverTopView;
@property(nonatomic,strong)UIView *coverLeftView;
@property(nonatomic,strong)UIView *coverRightView;
@property(nonatomic,strong)UIView *coverBottomView;

@property(nonatomic,assign)NSInteger version;
@end

@implementation HHQReaderViewController
{
    int num;
    BOOL upOrdown;
    NSTimer * timer;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    upOrdown = NO;
    num =0;
    
    self.version = [[UIDevice currentDevice].systemVersion integerValue];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.version >= 7) {
        [self initCapture];
        [self createOverView];
        [self startLineTime];
        [self cameraAnimationImageView];
    }else{
        [self startZbar];
        [self createOverView];
        [self startLineTime];
        [self cameraAnimationImageView];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.version >= 7) {
        [self.session stopRunning];
    }else{
        [self.zReaderView stop];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark -- Private

/**
 *  zBar二维码扫描
 */
-(void)startZbar
{
    ZBarReaderView *readview = [ZBarReaderView new]; // 初始化
    self.zReaderView = readview;
    readview.frame = self.view.bounds;  // 改变frame
    readview.readerDelegate = self;       // 设置delegate
    readview.allowsPinchZoom = NO;       // 不使用Pinch手势变焦
    readview.tracksSymbols = NO;
    readview.torchMode = 0;
    [self.view addSubview:readview];
    [readview start];
}
/**
 *  添加过场动画
 */
-(void)createOverView
{
    if (self.overView == nil) {
        self.overView = [[UIView alloc] initWithFrame:self.view.bounds];
        self.overView.backgroundColor = [UIColor clearColor];
    }
    
    [self.view addSubview:self.overView];
    for (UIView *subView in self.overView.subviews) {
        [subView removeFromSuperview];
    }
    
    UIImage *scanImage = [UIImage imageNamed:@"scan.png"];
    self.scaningImageView = [[UIImageView alloc] initWithImage:scanImage] ;
    self.scaningImageView.backgroundColor = [UIColor clearColor];
    self.scaningImageView.frame = CGRectMake((self.view.width - scanImage.size.width) / 2, 40,scanImage.size.width,scanImage.size.height);
    self.scaningImageView.clipsToBounds = YES;
    [self.overView addSubview:self.scaningImageView];
    
    
    UIImage *image = [UIImage imageNamed:@"scanline.png"];
    self.lineImageView = [[UIImageView alloc] initWithImage:image];
    self.lineImageView.backgroundColor = [UIColor clearColor];
    self.lineImageView.frame = CGRectMake((self.scaningImageView.width - image.size.width) / 2,-image.size.height,image.size.width, image.size.height);
    [self.scaningImageView addSubview:self.lineImageView];
    
    self.coverTopView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,self.view.width,self.scaningImageView.top)];
    self.coverTopView.backgroundColor = RGBCOLOR(68, 61, 58);
    self.coverTopView.alpha = 0.7f;
    [self.overView addSubview:self.coverTopView];
    
    self.coverLeftView = [[UIView alloc] initWithFrame:CGRectMake(0,self.coverTopView.bottom,self.scaningImageView.left,self.overView.height - self.coverTopView.height)];
    self.coverLeftView.backgroundColor = self.coverTopView.backgroundColor;
    self.coverLeftView.alpha = 0.7f;
    [self.overView addSubview:self.coverLeftView];
    
    self.coverRightView = [[UIView alloc] initWithFrame:CGRectMake((self.overView.width - self.coverLeftView.width),self.coverLeftView.top,self.coverLeftView.width, self.coverLeftView.height)];
    self.coverRightView.backgroundColor = self.coverTopView.backgroundColor;
    self.coverRightView.alpha = 0.7f;
    [self.overView addSubview:self.coverRightView];
    
    self.coverBottomView = [[UIView alloc] initWithFrame:CGRectMake(self.coverLeftView.right,self.scaningImageView.bottom,self.scaningImageView.width,self.overView.height - self.scaningImageView.bottom)];
    self.coverBottomView.backgroundColor = self.coverTopView.backgroundColor;
    self.coverBottomView.alpha = 0.7f;
    [self.overView addSubview:self.coverBottomView];

    
}

/**
 *  开场动画
 */
- (void)cameraAnimationImageView
{
    if (self.cameraTopImageView == nil) {
        UIImage *topImage = [[UIImage imageNamed:@"camera-blind-top-simple.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:10];
        self.cameraTopImageView = [[UIImageView alloc] initWithImage:topImage];
        self.cameraTopImageView.backgroundColor = [UIColor clearColor];
        
    }
    if (self.camearBottomImageView == nil) {
        UIImage *bottomImage = [[UIImage imageNamed:@"camera-blind-bottom-simple.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:42];
        self.camearBottomImageView = [[UIImageView alloc] initWithImage:bottomImage];
        self.camearBottomImageView.backgroundColor = [UIColor clearColor];
    }
    
    [self.overView addSubview:self.cameraTopImageView];
    [self.overView addSubview:self.camearBottomImageView];
    CGRect topRect = CGRectMake(0,0,self.view.width,self.view.height/2);
    CGRect bottomRect = CGRectMake(0,topRect.size.height - 40, self.view.width,self.view.height/2 + 40);
    self.cameraTopImageView.frame =topRect;
    self.camearBottomImageView.frame = bottomRect;
    topRect.origin.y = -topRect.size.height;
    bottomRect.origin.y = self.view.height;
    [UIView animateWithDuration:0.2f delay:0.8 options:UIViewAnimationOptionCurveLinear animations:^{
        self.cameraTopImageView.frame = topRect;
        self.camearBottomImageView.frame = bottomRect;
    } completion:^(BOOL finished) {
        [self.cameraTopImageView removeFromSuperview];
        [self.camearBottomImageView removeFromSuperview];
    }];
}

/**
 *  扫描中间横线动画
 */
-(void)animationLineView
{
    CGRect rect = self.lineImageView.frame;
    if (upOrdown == NO) {
        num ++;
        rect.origin.y = -self.lineImageView.image.size.height + 2*num;
        if (2*num >= (self.scaningImageView.height)) {
            upOrdown = YES;
        }
    }else {
        num --;
        rect.origin.y = -self.lineImageView.image.size.height + 2*num;
        if (num == 0) {
            upOrdown = NO;
        }
    }
    
    [UIView animateWithDuration:0.001 animations:^{
        self.lineImageView.frame = rect;
    }];
}

/**
 *  打开iOS7二维码扫描
 */
- (void)initCapture
{
    NSError *error;
    
    AVCaptureSession *session = [[AVCaptureSession alloc]init];
    self.session = session;
    // Device
    AVCaptureDevice *capDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:capDevice error:&error];
    
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc]init];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    
    [session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([session canAddInput:input]){
        [session addInput:input];
    }
    
    if ([session canAddOutput:output]){
        [session addOutput:output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
    
    // Preview
    if (self.preview == nil) {
        
    }
    AVCaptureVideoPreviewLayer *preview =[AVCaptureVideoPreviewLayer layerWithSession:session];
    preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    preview.frame =self.view.bounds;
    [self.view.layer addSublayer:preview];
    [session startRunning];
    
}
#pragma mark -- StartTimer
/**
 *  启动计时器，用于扫描动画
 */
-(void)startLineTime
{
    self.lineImageView.hidden = NO;
    if (timer == nil) {
        timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animationLineView) userInfo:nil repeats:YES];
    }
}

/**
 *  停止扫描
 */
-(void)stopLineTime
{
    [timer invalidate];
    timer = nil;
    if (self.version >= 7) {
        if ([self.session isRunning]) {
            [self.session stopRunning];
        }
    }else{
        [self.zReaderView stop];
    }
    self.lineImageView.hidden = YES;
}


#pragma mark -- Public
/**
 *  启动二维码扫描
 */
-(void)startQReader
{
    [self cameraAnimationImageView];
    if (self.version >= 7) {
        if ([self.session isRunning]) {
            return;
        }
        [self initCapture];
        [self createOverView];
        [self startLineTime];
    }else{
        [self startZbar];
        [self createOverView];
        [self startLineTime];
    }
}

/**
 *  停止二维码扫描
 */
-(void)stopQReader
{
    [self stopLineTime];
}

#pragma mark -- AVCaptureMetadataOutputObjectsDelegate
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    [self stopQReader];
    if ([metadataObjects count] >0){
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        if (self.QReaderFinish) {
            self.QReaderFinish(metadataObject.stringValue);
        }
    }
}

#pragma mark -- ZBarReaderViewDelegate
- (void)readerView:(ZBarReaderView *)readerView didReadSymbols:(ZBarSymbolSet *)symbols fromImage:(UIImage *)image
{
    // 得到扫描的条码内容
    const zbar_symbol_t *symbol = zbar_symbol_set_first_symbol(symbols.zbarSymbolSet);
    NSString *symbolStr = [NSString stringWithUTF8String: zbar_symbol_get_data(symbol)];
    if (symbolStr.length > 0) {
        [self stopQReader];
        if (self.QReaderFinish) {
            self.QReaderFinish(symbolStr);
        }
    }
}

@end
